<?php

namespace app\admin\controller\commission;

use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 服务套餐
 *
 * @icon fa fa-circle-o
 */
class Sale extends Backend
{

    /**
     * Sale模型对象
     * @var \app\admin\model\commission\Sale
     */
    protected $model = null;
    protected $dataLimit = 'auth'; //默认基类中为false，表示不启用，可额外使用auth和personal两个值
    protected $dataLimitField = 'id';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Admin();
    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            $result = Db::query("SELECT DATE_FORMAT(FROM_UNIXTIME(create_time), '%Y') AS year FROM fa_customer_service group by year");
            if (!$result) {
                $result = [
                    ['year' => date("Y")],
                    ['year' => date("Y", strtotime('-1 year'))]
                ];
            }
            $this->view->assign('year_list', $result);
            $this->view->assign('year', (int)date("Y"));
            $this->view->assign('month', (int)date("m"));
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    public function log($ids = '', $year_month = '')
    {
        $admin = $this->model::get($ids);

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            $this->assignconfig('id', $ids);
            $this->assignconfig('year_month', $year_month);
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$sort, $order, $offset, $limit] = $this->buildparams();


        $currTime = strtotime(date('Y-m', $year_month) . date('-d H:i:s'));
        $firstDay = date('Y-m-01', $year_month);
        $lastDay = strtotime("$firstDay +1 month -1 day");

        $package_ids = (new \app\admin\model\customer\Package)->where(['admin_id' => $ids])->column('package_id');

//        var_dump($firstDay);
//        var_dump(date('Y-m-d',$lastDay));


        //收款金额*%
        $where1 = [
            'create_time' => ['between', [strtotime($firstDay), $lastDay]],
            'package_id' => ['in', $package_ids],
            'sales_commission_type' => ['=', 0],
        ];
        //固定金额
        $where2 = [
            'create_time' => ['between', [strtotime($firstDay), $lastDay]],
            'package_id' => ['in', $package_ids],
            'sales_commission_type' => ['=', 1],
        ];
        //每月提成
        $where3 = [
            'start_time' => ['<=', $currTime],
            'end_time' => ['>=', $currTime],
            'package_id' => ['in', $package_ids],
            'sales_commission_type' => ['=', 2],
        ];


        $list = (new \app\admin\model\customer\Service())
            ->with(['customer'])
            ->where($where1)
            ->whereOr(function ($query) use ($where2) {
                $query->where($where2);
            })
            ->whereOr(function ($query) use ($where3) {
                $query->where($where3);
            })
            ->order('id', $order)
            ->paginate($limit);

        $data = $list->items();
        $data[] = [
            'id' => '合计',
            'customer_id' => 140,
            'package_id' => 55,
            'service_id' => 15,
            'service_name' => '-',
            'corporate_type' => 1,
            'standard_price' => '2400.00',
            'cost_type' => 1,
            'cost_price' => '650.00',
            'deal_price' => '0.00',
            'collection_price' => '0.00',
            'balance_price' => '0.00',
            'account_commission_type' => '-',
            'account_commission' => 0,
            'sales_commission_type' => '-',
            'sales_commission' => (new \app\admin\model\customer\Service())->where($where1)
                ->whereOr(function ($query) use ($where2) {
                    $query->where($where2);
                })
                ->whereOr(function ($query) use ($where3) {
                    $query->where($where3);
                })->sum('sales_commission'),
            'outworker_commission_type' => 0,
            'outworker_commission' => '0.00',
            'ledger_expenses' => '0.00',
            'create_time' => 1711611824,
            'month' => 12,
            'start_time' => 0,
            'end_time' => 0,
            'customer' => [
                'full_name' => '-',
                'idnumber' => '-',
                'corporate_name' => '-',
            ],
            'create_time_text' => '2024-03-28 15:43:44',
            'start_time_text' => '-',
            'end_time_text' => '-',
            'distance_days' => 359,
        ];

        $result = ['total' => $list->total(), 'rows' => $data];
        return json($result);
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null, $year_month = '')
    {

        $this->model = new \app\admin\model\customer\Service;


        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch('commission/sale/log/edit');

        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            if ($params['sales_commission_type'] == 0) {
                $params['sales_commission'] = ($row->deal_price - $row->cost_price) * ($params['sales_commission'] / 100);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


}
